package service

import (
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/gstr"
	"duoke/utils/orm"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/frame/g"
	"reflect"
)

var AccountSetting = new(accountSettingService)

type accountSettingService struct{}

func (s *accountSettingService) Save(c *gin.Context, req map[string]interface{}) error {
	accountR, _ := Request.Account(c)
	setting := new(tables.AccountSetting)
	has, err := orm.Db.Where("acid =?", accountR.Id).Get(setting)
	if err != nil {
		return err
	}
	var affected int64
	// 反射设置结构体值
	rve := reflect.ValueOf(setting).Elem()
	g.Dump(req["field"])
	rve.FieldByName(gstr.CamelString(gconv.String(req["field"]))).SetString(gjson.StructOrMap2Json(req["data"]))
	if has {
		affected, err = orm.Db.ID(setting.Id).Cols(gconv.String(req["field"])).Update(setting)
	} else {
		setting.Acid = accountR.Id
		affected, err = orm.Db.Insert(setting)
	}
	if affected == 0 {
		return nil
	}
	return err
}
func (s *accountSettingService) Info(c *gin.Context, field string) (map[string]interface{}, error) {
	//accountR, _ := Request.Account(c)
	setting := new(tables.AccountSetting)
	_, err := orm.Db.Where("acid =?", 1).Get(setting)
	if err != nil {
		return nil, err
	}
	//if !has {
	//	return nil, errors.New("数据未设置")
	//}
	rve := reflect.ValueOf(*setting)
	var data map[string]interface{}
	gjson.Json2StructOrMap(rve.FieldByName(gstr.CamelString(field)).String(), &data)
	return data, nil
}
func (s *accountSettingService) InfoById(id int, field string) (map[string]interface{}, error) {
	setting := new(tables.AccountSetting)
	_, err := orm.Db.Where("acid =?", id).Get(setting)
	if err != nil {
		return nil, err
	}
	//if !has {
	//	return nil, errors.New("数据未设置")
	//}
	rve := reflect.ValueOf(*setting)
	var data map[string]interface{}
	gjson.Json2StructOrMap(rve.FieldByName(gstr.CamelString(field)).String(), &data)
	return data, nil
}

// 通过mchId获取配置信息
func (s *accountSettingService) InfoByMchId(openid string, field string) (map[string]interface{}, error) {
	setting := new(tables.AccountSetting)
	_, err := orm.Db.Where("miniprogram like ?", "%pay_mch_id:1645139391%").Get(setting)
	if err != nil {
		return nil, err
	}
	//if !has {
	//	return nil, errors.New("数据未设置")
	//}
	rve := reflect.ValueOf(*setting)
	var data map[string]interface{}
	gjson.Json2StructOrMap(rve.FieldByName(gstr.CamelString(field)).String(), &data)
	return data, nil
}
